package com.lq.rocketmq.order;

import com.lq.rocketmq.config.MyConstant;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.List;

/**
 * @ClassName OrderConsumer
 * @Description 同步消息消费者
 * @Author LQ
 * @Date 2021/5/15 23:48
 * @Version 1.0
 */
public class OrderConsumer {
    public static void main(String[] args) throws MQClientException {
        // 创建消费者
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(MyConstant.MSG_GROUP);
        // 指定nameserver
        consumer.setNamesrvAddr(MyConstant.NAMESRV_ADDR);
        // 订阅Topid和Tag
        consumer.subscribe(MyConstant.TOPIC, "*");
        // 注册消息监听器,MessageListenerOrderly 对于同一个消息队列,使用同一个线程
        consumer.registerMessageListener(new MessageListenerOrderly() {
            /**
             *
             * @param msgs
             * @param context
             * @return
             */
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                for (MessageExt msg : msgs) {
                    System.out.println("线程名称【" + Thread.currentThread().getName() + "】:" + new String(msg.getBody()));
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        // 开启消费者
        consumer.start();
        System.out.println("------>消费者启动");
    }


}
